package com.swf.seed.netty.common;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPoolFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;

/**
 * 默认的 Channel 连接池
 *
 * @author gavin
 * @create 13-7-30
 * @since 1.0.0
 */
public class DefaultChannelPool implements ChannelPool {

    private ObjectPool<Channel> channelObjectPool;

    public DefaultChannelPool(final ChannelGroup poolableChannelGroup) {
        this.channelObjectPool = new GenericObjectPoolFactory<Channel>(
                new BasePoolableObjectFactory<Channel>(){
            //
            private ChannelGroup pooledChannelGroup = new DefaultChannelGroup();

            public Channel makeObject() throws Exception {
                for(Channel poolableChannel : poolableChannelGroup) {
                    if(pooledChannelGroup.contains(poolableChannel)) {
                        continue;
                    }
                    pooledChannelGroup.add(poolableChannel);
                    return poolableChannel;
                }
                //
                throw new UnsupportedOperationException("没有更多的 Channel 可用！");
            }
        }, poolableChannelGroup.size()).createPool();
    }

    public Channel borrowChannel() throws Exception {
        return channelObjectPool.borrowObject();
    }

    public void returnChannel(Channel channel) throws Exception {
        this.channelObjectPool.returnObject(channel);
    }

}
